﻿using MaiPlanServer.Dto;
using MaiPlanServer.IServices.IOrganizationaServices;
using MaiPlanServer.Model;
using MaiPlanServer.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MaiPlanServer.API.Controllers.Organizational
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentManageController : ControllerBase
    {
        public DepartmentManageController(IDepartmentManageServices db)
        {
            Db = db;
        }

        public IDepartmentManageServices Db { get; }

        /// <summary>
        /// 获取部门管理数据
        /// </summary>
        /// <param name="DName">部门名称</param>
        /// <param name="Status">部门状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(string DName, string Status)
        {
            List<sys_deptDto> DList = new List<sys_deptDto>();
            try
            {
                var list = await Db.GetDepartmentAsync(DName, Status);
                DList = GetItem(list);
                return Ok(BaseState.CreateInstance(200, "请求成功", DList));
            }
            catch (System.Exception ex)
            {
                //后续写日志
            }
            return Ok(BaseState.CreateInstance(BaseState.RequestError, "请求失败ex"));
        }
        [NonAction]
        private List<sys_deptDto> GetItem(IEnumerable<sys_deptDto> list)
        {
            List<sys_deptDto> TreeList = new List<sys_deptDto>();
            var parent = list.Where(x => string.IsNullOrEmpty(x.parent_id));
            var lists = parent.ToList();
            var child = list.Where(x => !string.IsNullOrEmpty(x.parent_id));
            var list111 = child.ToList();
            foreach (var item in parent)
            {
                //判断当前父元素有没有子元素
                var curr_child = child.Where(x => x.parent_id == item.dept_id);
                if (curr_child.Any())
                {
                    GetSubItem(item, list, curr_child);
                }
                TreeList.Add(item);
            }
            if (!parent.Any())
            {
                foreach (var item in child)
                {
                    TreeList.Add(item);
                }
            }
            return TreeList;
        }
        [NonAction]
        public void GetSubItem(sys_deptDto parent, IEnumerable<sys_deptDto> list, IEnumerable<sys_deptDto> child)
        {
            foreach (var item in child)
            {
                var curr_child = list.Where(x => x.parent_id == item.dept_id);
                if (curr_child.Any())
                {
                    GetSubItem(item, list, curr_child);
                }

                parent.Children.Add(item);
            }
        }
        /// <summary>
        /// 新增部门
        /// </summary>
        /// <param name="model">部门模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] sys_dept model)
        {
            try
            {
                model.dept_id = Guid.NewGuid().ToString();
                model.create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var result = await Db.AddAsync(model);
                if (result)
                {
                    return Ok(BaseState.CreateInstance(200, "新增成功"));
                }
            }
            catch (System.Exception ex)
            {
                //后续写日志
            }
            return Ok(BaseState.CreateInstance(-1, "新增失败，服务器异常"));
        }
        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="model">部门模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Put([FromForm] sys_dept model)
        {
            try
            {
                model.update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var result = await Db.PutAsync(model);
                if (result)
                {
                    return Ok(BaseState.CreateInstance(200, "修改成功"));
                }
            }
            catch (System.Exception ex)
            {
                //后续写日志
            }
            return Ok(BaseState.CreateInstance(-1, "修改失败，服务器异常"));
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="Id">部门Id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del(string Id)
        {
            try
            {
                var result = await Db.DelAsync(Id);
                if (result)
                {
                    return Ok(BaseState.CreateInstance(200, "删除成功"));
                }
            }
            catch (System.Exception ex)
            {
                //后续写日志
            }
            return Ok(BaseState.CreateInstance(-1, "删除失败，服务器异常"));
        }
    }
}
